<?php

namespace App\Exports;

use Illuminate\Http\Request;
use App\Models\MealShop;
use App\Models\MealOrder;
use Maatwebsite\Excel\Concerns\FromCollection;
use DB;

class ShopExport implements FromCollection
{
	private $param = [];
	public function __construct($param=false)
	{	
		$this->param = $param;
	}
    /**
    * @return \Illuminate\Support\Collection
    */
    public function collection()
    {
    	DB::connection()->enableQueryLog();
    	$param = $this->param;
    	$sql = MealOrder::where(function($q) use($param){
        	if(!empty($param['starttime'])){
	        	return $q->whereRaw('lexiang_meal_order.insert_time between '.strtotime($param['starttime']).' and '.strtotime($param['endtime']));
        	}
        })->whereRaw('lexiang_meal_order.order_status>-1')->whereRaw('lexiang_meal_order.shops_id=lexiang_meal_shop.shop_id')->selectRaw('count(*)');
        $order_sumsql = MealOrder::where(function($q) use($param){
        	if(!empty($param['starttime'])){
	        	return $q->whereRaw('lexiang_meal_order.insert_time between '.strtotime($param['starttime']).' and '.strtotime($param['endtime']));
        	}
        })->whereRaw('lexiang_meal_order.order_status>-1')->whereRaw('lexiang_meal_order.shops_id=lexiang_meal_shop.shop_id')->selectRaw('sum(lexiang_meal_order.meal_order_price)');
        $d = MealShop::where(function($q){
        	if(session('company_id')){
        		return $q->where('lexiang_meal_shop.company_id','=',session('company_id'));
        	}
        })->selectRaw('lexiang_meal_shop.shop_id,lexiang_meal_shop.shop_name,lexiang_meal_shop.shop_tel,('.$sql->toSql().') as orders_count,('.$order_sumsql->toSql().') as orders_sum')
        ->get();
        $d->prepend(['id','名称','手机号','订单数','收入额（元）']);
        return $d;
    }
}
